package
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	
	
	[SWF(width="600", height="500", backgroundColor="0xeeeeee")]
	public class BrickGame extends Sprite
	{
		
		/**
		 * Ball 
		 */		
		private var ball:Ball;
		/**
		 * 砖块数组 
		 */		
		private var brickArr:Array = [];

		private var board:Board;
		
		public function BrickGame()
		{
			trace("BrickGame");
			init();
		}
		
		private function init():void{
			initBall();
			initBricks();
			initBoard();
			this.addEventListener(Event.ENTER_FRAME, update);
		}
		
		protected function update(event:Event):void
		{
			ball.update();
			board.update();
			
			hitTestBallAndBoard();
			hitTestBallAndBircks();
		}
		/**
		 * 小球和砖块的碰撞检测和处理 
		 * 
		 */	
		private function hitTestBallAndBircks():void
		{
			for (var i:int = brickArr.length - 1; i >= 0 ; i--) 
			{
				var brick:IDispose = brickArr[i];
				if( DisplayObject(brick).hitTestObject( ball ) )
				{
					// 从数组中移除砖块
					brickArr.splice( i, 1 );
					// 删除砖块
					removeChild( DisplayObject(brick) );
					// 小球速度反向
					ball.reverseTB();
					// 销毁砖块
					brick.dispose()
					
				}
			}
			
		}
		/**
		 * 小球和挡板的碰撞检测和处理 
		 * 
		 */		
		private function hitTestBallAndBoard():void
		{
			if( ball.hitTestObject( board ) )
			{
				ball.y = board.y - board.height / 2 - ball.radius;
				ball.reverseTB();
			}
		}
		/**
		 * 初始化挡板 
		 * 
		 */		
		private function initBoard():void
		{
			board = new Board();
			this.addChild( board );
			board.y = 460;
		}
		/**
		 * 初始化砖块 
		 * 
		 */		
		private function initBricks():void
		{
			for (var j:int = 0; j < 6; j++) 
			{
				for (var i:int = 0; i < 8; i++) 
				{
					var brick:Brick = new Brick();
					this.addChild( brick );
					
					brick.x = 10 + 70 * i;
					brick.y = 10 + 25 * j;
					
					brickArr.push( brick );
				}
			}
			
			
			
		}
		/**
		 * 初始化小球 
		 * 
		 */	
		private function initBall():void
		{
			ball = new Ball();
			this.addChild( ball );
			
			ball.x = ball.y = 100;
			
			ball.updateSpeed( 10,10 );
		}
	}
}